<template>
  <div>
    <el-page-header @back="router.push('/login')" content="注册"></el-page-header>
    <el-divider></el-divider>

    <el-row>
      <el-col :span="12" :offset="6">
        <el-form ref="form" :model="userInfo" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="userInfo.password" type="password" />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="userInfo.conformPassword" type="password" />
          </el-form-item>
          <el-form-item label="年龄">
            <el-input-number v-model="userInfo.age" :min="10" :max="100" />
          </el-form-item>
          <el-form-item label="城市">
            <el-input v-model="userInfo.city" />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio v-model="userInfo.gender" :label="0">保密</el-radio>
            <el-radio v-model="userInfo.gender" :label="1">男</el-radio>
            <el-radio v-model="userInfo.gender" :label="2">女</el-radio>
          </el-form-item>

          <el-form-item>
            <el-col :span="4">
              <el-button type="primary" @click="onSubmit">注册</el-button>
            </el-col>
            <el-button type="danger">
              <router-link to="/login">登录</router-link>
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>


</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import { registerService } from '@/services/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userInfo = ref({ username: '', password: '', conformPassword: '', age: 20, city: '北京', gender: 0 })


async function onSubmit() {
  const { username, password, conformPassword } = userInfo.value
  if (!username || !password) {
    ElMessage({ message: '请输入用户名和密码', type: 'error', showClose: true })
    return
  }
  if (password !== conformPassword) {
    ElMessage({ message: '两次密码不一致', type: 'error', showClose: true })
    return
  }

  const responseModel = await registerService(userInfo.value)
  console.log('register page==>responseModel\n', responseModel)
  const { ok, message } = responseModel // responseModel 一定包含 ok, message
  // 注册新用户失败
  if (!ok) {
    ElMessage({ message, type: 'error', showClose: true })
    return
  }
  // 注册成功,跳转登录页
  ElMessageBox.confirm('是否跳转登录页?', '注册成功', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'success'
    }
  ).then(() => {
    ElMessage({ type: 'success', message: '是,跳转到登录页' })
    router.push('/login')
  })
    .catch(() => ElMessage({ type: 'info', message: '否,留在当前页' }))
}

</script>



